<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of cdkeygiftbag
 *
 * @author Dragon.hu
 */
defined('BASEPATH') or die('forbidden');

class Cdkeygiftbag_Controller extends Controller {

    private $inc;
    private $center_connect; //动态礼包表
    private $typelist; //type表
    private $actobjectlist; //作用对象
    private $kindlist; //物品类型
    private $colorlist; //物品颜色
    private $baglimitlist; //拾取状态
    private $gettypelist; //获得方式
    private $professionlist; //职业种类

    function _init() {
        check_level(50, segment(0), segment(1), segment(2, 'index'));
        $this->inc = $this->config['inc'];
//        $area_host = !empty($_SESSION['area_selected_host']) ? $_SESSION['area_selected_host'] : '';
//        if ($area_host == '') {
//        	echo "<script>alert('" . translate('C_SELECT_AREA_TEXT') . "');</script>";
//        	return;
//        }
        
        //把type表读到内存中来
        $type_connect =  $this->load->database('type_db');
        $sql = "SELECT id, name FROM type_object ";
        $type_connect->query($sql);
        while ($row = $type_connect->get_array()) {
            //几个特殊的标识需要转换下
            $this->typelist[$row['id']] = $row['name'];
        }
        $this->typelist = get_type_object_id_name();

        $type_connect->free_all();

        //本页面连中心服务器
        $this->center_connect = $this->load->database('db');

        $this->actobjectlist = array('0' => '自己', '1' => '队友', '2' => '光环', '3' => '帮派');
        $this->kindlist = array('10' => '装备', '11' => '材料', '12' => '时装', '13' => '消耗品', '14' => '任务物品');
        $this->colorlist = array('0' => '不分颜色', '1' => '白色', '2' => '蓝色', '3' => '紫色', '4' => '粉色', '5' => '橙色', '6' => '普通', '7' => '高级', '8' => '节日', '9' => '稀有');
        $this->baglimitlist = array('0' => '自由交易', '1' => '装备绑定', '2' => '拾取绑定');
        $this->gettypelist = array('0' => '掉落', '1' => '商城购买', '2' => '金币', '3' => '通用');
        $this->professionlist = array('-1' => '通用', '0' => '战士', '1' => '法师', '2' => '炮手', '3' => '牧师');
        //把数组传入到参数中去
        $this->view->assign("actobjectlist", $this->actobjectlist);
        $this->view->assign("kindlist", $this->kindlist);
        $this->view->assign("colorlist", $this->colorlist);
        $this->view->assign("baglimitlist", $this->baglimitlist);
        $this->view->assign("gettypelist", $this->gettypelist);
        $this->view->assign("professionlist", $this->professionlist);
    }

    function index() {
        $this->view->display("cdkey/cdkeygiftbag/index");
    }

    function flexigrid() {
        list($colkey, $colsinfo, $where, $sortname, $sortorder, $offset, $rp, $page) = $this->common->get_flexigrid_params();
        $sql = "SELECT COUNT(*) AS num FROM dynamic_type_object WHERE {$where}"; 
        $one = $this->center_connect->one($sql);
        $total = $one['num']; 
        $orderby = $sortname ? "ORDER BY {$sortname} {$sortorder} " : "";
        $sql = "SELECT {$colsinfo} FROM dynamic_type_object WHERE {$where} {$orderby} LIMIT {$offset},{$rp}";
        $this->center_connect->query($sql);
        while ($row = $this->center_connect->get_array()) {
            //几个特殊的标识需要转换下
            $row['actobject'] = $this->actobjectlist[$row['actobject']];
            $row['kind'] = $this->kindlist[$row['kind']];
            $row['color'] = $this->colorlist[$row['color']];
            $row['baglimit'] = $this->baglimitlist[$row['baglimit']];
            $row['gettype'] = $this->gettypelist[$row['gettype']];

            $rows[] = array('id' => $row['id'], 'cell' => $row);
        }
        $result = array(
            'page' => $page,
            'total' => $total,
            'rows' => $rows
        );

        echo json_encode($result);
    }

    function add() {
        set_time_limit(30);
        if (is_submit()) {
            $rowdata = $_POST['row'];
            //print_r($rowdata);
            //exit(0);
            for ($i = 0; $i < count($rowdata['item']); $i++) {
                //提取数据中的 objectid出来
                $len = stripos($rowdata['item'][$i], '(') == 0 ? 10 : stripos($rowdata['item'][$i], '(');
                $rowdata['item'][$i] = substr($rowdata['item'][$i], 0, $len);
            }
            //查找最大的数值出来
            //$one = $this->center_connect->one("SELECT MAX(giftbag_objectid) AS maxid FROM dynamic_giftbag");
            //$maxid = $one['maxid'] + 1;
            //$rowdata['type_id'] = $maxid;
            //在dynamic_type_object中添加一项目
            $sql = "insert into dynamic_type_object(`id`,`name`,`objecticon`,`describe`) values('$rowdata[id]','$rowdata[name]','$rowdata[objecticon]','$rowdata[describe]')";
            //echo " sql:$sql ";

            //$curId = 0;
            $curId = $rowdata['id'];
            if (true == $this->center_connect->query($sql)) {
                //得到当前插入数据的id
                //$curId = $this->center_connect->insert_id();
                //echo " curId:$curId ";

            } //else {
                //cp_tips("error");
               // return;
            //}

            //此数值大于0，则是出错了。。。
            $result = 0;

            $allot_ret = $this->center_connect->execute("insert into dynamic_giftbagallot(giftbagid,giftbagtype,gettype,gettimes,timetype,gmtype,isopen)"
                    . " values($curId,0,0,1,0,1,0)");
            if($allot_ret==FALSE){
                $result++;
            }
            $i = 0;
            //添加的项目数量不为空，且有数据则添加
            while ((!empty($rowdata["item"][$i])) && (!empty($rowdata["amount"][$i]))) {
                $sql = "insert into dynamic_giftbagdetail(giftbagid,objectid,profession,mincount,maxcount,getratio,limittype,limitcondition,validtime,isopen) values($curId, " . $rowdata['item'][$i] ." , " . $rowdata['profession'][$i] .  " ,  " . $rowdata['amount'][$i] .  " ,  " . $rowdata['amount'][$i] . " ,10000,0,0,0,0)";

                //echo " sql$i :$sql ";
                if (NULL == $this->center_connect->execute($sql)) {
                    //echo " err $i ";
                    //出错了。。。
                    $result = $result + 1;
                    break;
                }
                $i++;
            }
            unset($rowdata['item'], $rowdata['amount']);

            //if (0 == $result) {
                //向http服务器发验证消息,待添加 。。。。
            	//$strResult = vpost($this->config['host_url'] . "messageid=200001&action=51");
            //	$area_host = ! empty ( $_SESSION ['area_selected_host'] ) ? $_SESSION ['area_selected_host'] : '';
            //    $strResult = vpost($area_host . "messageid=200001&action=51");
                //print_r($strResult);
                //exit(0);
            //}
            //if ($strResult != '0' || $strResult === FALSE) {
            //    $result = $result + 1;
            //    echo " error ";
           // } else {
                insert_log(translate('MENU_ACTIVITY_GIFTBAG'),translate('ADD'), NULL, array("name" => $this->config['host_url'] . 'area:' . array_to_stringparam($rowdata)));
            //}
            cp_tips($result == 0 ? "success" : "error");
        }

        $this->view->display("cdkey/cdkeygiftbag/add");
    }

    function del($id = 0) {
        $c = 0;
        $r = '';
        if ($id === 0) {
            json_output($c, translate('C_INVALID_PARAM_ID'));
        }

        $strResult = 0;

        $sql = "delete from dynamic_type_object where id = $id";
        if (false == $this->center_connect->execute($sql)) {
            $strResult = $strResult + 1;
        }

        $sql = "delete from dynamic_giftbagallot where giftbagid = $id";
        if (false == $this->center_connect->execute($sql)) {
            $strResult = $strResult + 1;
        }
        
        $sql = "delete from dynamic_giftbagdetail where giftbagid = $id";
        if (false == $this->center_connect->execute($sql)) {
            $strResult = $strResult + 1;
        }

        //$strResult = vpost($this->config['host_url'] . 'type_id=' . $id . "&action=36");

        if ($strResult != '0' || $strResult === FALSE) {
            $c = 0;
            $r = translate('C_TIPS_ERROR_TEXT');
        } else {
            $c = 1;
            insert_log(translate('MENU_ACTIVITY_GIFTBAG'),translate('DEL'), array('id'=>$id));
            $r = translate('ACTIVITY_GIFTBAG_DEL');
        }
        json_output($c, $r);
    }

    function edit($id = 0) {
        //echo " id = $id ";
        //var_dump($_REQUEST);
        $rowdata = array();
        if (is_submit()) { //编辑修改
            //接收收到的数据
            $rowdata = $_POST['row'];
            //var_dump($rowdata);

            //操作结果 是否正确
            $result = 0;

            $sql = "update dynamic_type_object set `name` = '$rowdata[name]',`objecticon`='$rowdata[objecticon]',
					`describe`='$rowdata[describe]' where id = $id ";
            echo " sql0:$sql ";
            if (false == $this->center_connect->execute($sql)) {
                echo " $sql error ";
                $result = $result + 1;
            }
            /*
              //更新数据
              $table = "dynamic_type_object";
              $value = array(`name` => $rowdata['name'],`objecticon`=>$rowdata['objecticon'],	`describe`=>$rowdata['describe'] );
              $where = array('id'=>$id);

              if(false == $this->center_connect->update($table, $value, $where))
              {
              echo " $sql error ";
              cp_tips("error");
              return;
              }
             */
            //先删除已存在的数据
            $sql = "delete from dynamic_giftbagdetail where giftbagid = $id";
            echo " sql1:$sql ";
            if (false == $this->center_connect->execute($sql)) {
                echo " $sql error ";
                $result = $result + 1;
            }
            //var_dump($rowdata);
            $i = 0;
            //添加的项目数量不为空，且有数据则添加
            while ((!empty($rowdata["item"][$i])) && (!empty($rowdata["amount"][$i]))) {
                //类型表，要去掉后面的中文字符
                $len = stripos($rowdata['item'][$i], '(') == 0 ? 10 : stripos($rowdata['item'][$i], '(');
                $rowdata['item'][$i] = substr($rowdata['item'][$i], 0, $len);

                $sql = "insert into dynamic_giftbagdetail(giftbagid,objectid,profession,mincount,maxcount,getratio,limittype,limitcondition,validtime,isopen) values($id, " . $rowdata['item'][$i] ." , " . $rowdata['profession'][$i] .  " ,  " . $rowdata['amount'][$i] .  " ,  " . $rowdata['amount'][$i] . " ,10000,0,0,0,0)";

                echo " sql2-$i :$sql ";
                if (NULL == $this->center_connect->execute($sql)) {
                    echo " sql2-$i:$sql error ";
                    //出错了。。。
                    $result = $result + 1;
                    break;
                }
                $i++;
            }
            unset($rowdata['item'], $rowdata['amount']);

            if (0 == $result) {
                //向http服务器发验证消息,待添加 。。。。
                //$strResult = vpost($this->config['host_url'] . "messageid=200001&action=51");
                $area_host = ! empty ( $_SESSION ['area_selected_host'] ) ? $_SESSION ['area_selected_host'] : '';
                $strResult = vpost($area_host . "messageid=200001&action=51");
                //打日志出来
                insert_log(translate('MENU_ACTIVITY_GIFTBAG'),translate('EDIT'), NULL, array("name" => $this->config['host_url'] . 'area:' . array_to_stringparam($rowdata)));
            }
            cp_tips($result == 0 ? "success" : "error");
        }

        //是否有错误。。。
        $strResult = 0; //0表示没有错误
        //先查下礼包的基本数据
        $sql = "SELECT * FROM dynamic_type_object WHERE id={$id}";
        $row = $this->center_connect->query($sql);
        if ($row = $this->center_connect->get_array()) {
            //print_r($row);
            $rowdata['name'] = $row['name'];
            $rowdata['objecticon'] = $row['objecticon'];
            $rowdata['describe'] = $row['describe'];
        } else {
            $strResult = $strResult + 1;
            echo "sql2:$sql";
            error(translate('C_INVALID_PARAM_ID', $id));
        }
        //var_dump($row);
        //再查下当前礼包包含的物品
        $sql = "SELECT * FROM dynamic_giftbagdetail WHERE giftbagid={$id}";
        $this->center_connect->query($sql);

        $num = 0;
        while ($row = $this->center_connect->get_array()) {
            //print_r($row);
            $rowdata['item'][$num] = $row['objectid'] . "(" . $this->typelist[$row['objectid']] . ")";
            $rowdata['amount'][$num] = $row['mincount'];
            $rowdata['profession'][$num] = $row['profession'];

            $num = $num + 1;
        }

        //print_r($rowdata);

        $this->view->assign("num", $num);
        $this->view->assign("row", $rowdata);
        $this->view->display("cdkey/cdkeygiftbag/edit");
    }

    function multi() {
        $type = $this->input->post("type");
        $ids = $this->input->post("ids");
        //$_SESSION['glql']='999999';exit();
        var_dump($type);
        var_dump($ids);
        $c = 0;
        $r = '';
        $allids = $ids = explode(',', $ids);
        if (count($ids) == 0) {
            $r = translate('C_INVALID_PARAMS');
        } else {
            $ids = "'" . implode("','", $ids) . "'";
            if ($type == 'delete') {
                //$strResult = vpost($this->config['host_url'] . 'type_id=' . $id . "action=36");
                //$c = (int) $strResult == 0 ? 1 : 0;
                insert_log(translate('MENU_ACTIVITY_GIFTBAG'),translate('DEL'), array('ids'=>implode(",", $allids)));
                $c = 1;
            } else {
                $r = translate('C_INVALID_PARAMS');
            }
        }
        json_output($c, $r);
    }

}

?>
